package com.xgp.pool;

import java.util.concurrent.*;

/**
 * 自定义线程池
 */
public class Demo02 {
/*    public ThreadPoolExecutor(int corePoolSize,   //核心线程数
                              int maximumPoolSize,  //最大线程数
                              long keepAliveTime,   //超时等待
                              TimeUnit unit,        //超时等待的单位
                              BlockingQueue<Runnable> workQueue,    //阻塞队列
                              ThreadFactory threadFactory,      //线程池工厂
                              RejectedExecutionHandler handler) {*/     //拒绝策略
    public static void main(String[] args) {
        /**
         * 最大线程应该如何定义
         * 1，CPU密集型     几何就是几，可以保持Cpu的效率最高
         * 2，IO密集型   >   判断程序中十分耗IO的线程
         */
        System.out.println(Runtime.getRuntime().availableProcessors());
        ExecutorService pool = new ThreadPoolExecutor(
                2,
                5,
                3,
                TimeUnit.SECONDS,
                new LinkedBlockingDeque<>(3),
                Executors.defaultThreadFactory(),
//                new ThreadPoolExecutor.AbortPolicy()    //会抛出异常的实现类
//                new ThreadPoolExecutor.CallerRunsPolicy()  //哪来的去哪里
//                new ThreadPoolExecutor.DiscardOldestPolicy()    //不会抛出异常，会丢掉任务
                new ThreadPoolExecutor.DiscardPolicy()       //尝试会和第一个竞争
        );


        try{
            for(int i = 0;i < 10;i++) {
                //使用线程池去创建
                pool.execute(() -> {
                    System.out.println(Thread.currentThread().getName() + " OK");
                });
            }
        }catch (Exception e) {
            e.printStackTrace();
        }finally {
            //关闭线程池
            pool.shutdown();
        }
    }
}
